package com.juyu.miliao.api.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.api.dao.redis.DynamicCommentInfoRedisDao;
import com.juyu.miliao.api.dao.redis.DynamicInfoRedisDao;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.CommentReplyInfo;
import com.juyu.miliao.api.domain.DynamicCommentInfo;
import com.juyu.miliao.api.domain.dto.DynamicCommentInfoDTO;
import com.juyu.miliao.api.domain.vo.CommentReplyDetailInfo;
import com.juyu.miliao.api.domain.vo.DynamicCommentInfoVo;
import com.juyu.miliao.api.domain.vo.DynamicDetailInfoVo;
import com.juyu.miliao.api.domain.vo.DynamicSourceInfoVO;
import com.juyu.miliao.api.util.PageUtil;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xuanqicheng
 * @create 2019-21-12:57
 */
@Service
public class DynamicCommentInfoService {

    private static final Logger logger = LoggerFactory.getLogger("dynamicCommentLog");
    @Autowired
    private DynamicCommentInfoRedisDao dynamicCommentInfoRedisDao;

    @Autowired
    private DynamicInfoRedisDao dynamicInfoRedisDao;

    @Autowired
    private UserInfoCache userInfoCache;

    @Autowired
    private VestRobotMessageService vestRobotMessageService;


    /**
     * 添加评论信息
     * @param dynamicCommentInfoDTO
     */
    public void addDynamicComment(DynamicCommentInfoDTO dynamicCommentInfoDTO) throws IOException {
        String temp = NetEaseCloudUserService.getYunTextCheck(dynamicCommentInfoDTO.getComment());

        logger.info("动态评论反垃圾响应内容："+temp+"，评论动态id："+dynamicCommentInfoDTO.getDynamicId()
                +",评论内容："+dynamicCommentInfoDTO.getComment());

        JSONObject json = JSONObject.parseObject(temp);

        int code = json.getIntValue("code");
        String msg = json.getString("msg");
        if(code == 200){
            JSONObject result = json.getJSONObject("result");
            int action = result.getIntValue("action");
            if(action==0){
                DynamicCommentInfo dynamicCommentInfo = dynamicCommentInfoRedisDao.addDynamicComment(dynamicCommentInfoDTO);

                dynamicCommentInfoRedisDao.incrementDynamicCommentNumber(dynamicCommentInfoDTO.getFromUserId());
                //发送im 消息
                sendIM(dynamicCommentInfo);

            }else{
                logger.info("动态评论发垃圾不通过，评论动态id："+dynamicCommentInfoDTO.getDynamicId()
                        +",评论内容："+dynamicCommentInfoDTO.getComment());
                throw new ConsumeRuntimeException("4112","评论内容违规", HttpStatus.BAD_REQUEST);
            }
        }else{
            logger.error("动态评论反垃圾响应异常，状态码:"+code+"，状态描述："+msg+"评论动态id："+dynamicCommentInfoDTO.getDynamicId()
                    +",评论内容："+dynamicCommentInfoDTO.getComment());
        }


    }

    /**
     * 发送im消息
     * @param dynamicCommentInfo
     */
    private void sendIM(DynamicCommentInfo dynamicCommentInfo) {
        DynamicDetailInfoVo dynamicDetailInfoVo=dynamicInfoRedisDao.getDynamicInfoById(dynamicCommentInfo.getDynamicId());
        if(!dynamicDetailInfoVo.getUserId().equals(dynamicCommentInfo.getFromUserId())) {
            long fromUserId = dynamicCommentInfo.getFromUserId();

            UserCacheVo fromUser = userInfoCache.getUserCacheInfo(fromUserId);

            String fromUserIcon = fromUser.getIcon();

            long dynamicId = dynamicDetailInfoVo.getDynamicId();

            long commentId = dynamicCommentInfo.getId();

            String dynamicSourceUrl = "";

            DynamicSourceInfoVO dynamicSourceInfoVO = dynamicDetailInfoVo.getDynamicSourceUrls().get(0);
            if (dynamicDetailInfoVo.getSourceType() == 1) {
                dynamicSourceUrl = dynamicSourceInfoVO.getDynamicSourceUrl();
            } else {
                dynamicSourceUrl = dynamicSourceInfoVO.getVideoImgUrl();
            }

            long commentReplyId = 0;

            String message = fromUser.getNickName() + "评论你的动态：" + dynamicDetailInfoVo.getDynamicTextContent();

            JSONObject json = new JSONObject();
            json.put("fromUserId", fromUserId);
            json.put("fromUserIcon", fromUserIcon);
            json.put("dynamicId", dynamicId);
            json.put("commentId", commentId);
            json.put("dynamicSourceUrl", dynamicSourceUrl);
            json.put("commentReplyId", commentReplyId);
//            json.put("type", 4);

            int stat = EnumType.TEXT_MESSAGE.state;

            vestRobotMessageService.getSendMsg(dynamicDetailInfoVo.getUserId(), EnumType.DYNAMIC_USER_ID.state, message,
                    json.toJSONString(), stat);
        }

    }

    public Object getDetailInfo(long id) {

        DynamicCommentInfo dynamicCommentInfo =dynamicCommentInfoRedisDao.getDynamciCommentInfoByCommentId(id);

        if(dynamicCommentInfo!=null){

            DynamicDetailInfoVo dynamicVo = dynamicInfoRedisDao.getDynamicInfoById(dynamicCommentInfo.getDynamicId());

            DynamicCommentInfoVo dynamicCommentInfoVo = new DynamicCommentInfoVo();

            BeanUtils.copyProperties(dynamicCommentInfo, dynamicCommentInfoVo);

            UserCacheVo commentUserInfo = userInfoCache.getUserCacheInfo(dynamicCommentInfo.getFromUserId());

            int nowYear=LocalDateTime.now().getYear();

            int commentYear = dynamicCommentInfoVo.getCommentTime().getYear();

            String times;
            if(nowYear==commentYear){
                LocalDateTime time = dynamicCommentInfoVo.getCommentTime();
                times = time.getMonthValue()+"-"+time.format(DateTimeFormatter.ofPattern("dd HH:mm"));
            }else{
                times = dynamicCommentInfoVo.getCommentTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            }

            dynamicCommentInfoVo.setFromUserNickName(commentUserInfo.getNickName())
                    .setFromUserIcon(commentUserInfo.getIcon())
                    .setFromUserAge(commentUserInfo.getAge())
                    .setFromUserIsHost(commentUserInfo.getIsHost())
                    .setFromUserIsVip(commentUserInfo.getIsVip())
                    .setVipLevel(commentUserInfo.getVipLevel())
                    .setStar(commentUserInfo.getStar())
                    .setFromUserVGrade(commentUserInfo.getVGrade())
                    .setFromUserMGrade(commentUserInfo.getMGrade())
                    .setFromUserSex(commentUserInfo.getSex())
                    .setShowTime(times);

            dynamicCommentInfoVo.setCommentId(dynamicCommentInfo.getId());

            if(dynamicCommentInfoVo.getFromUserId().equals(dynamicVo.getUserId())){
                dynamicCommentInfoVo.setIsAuthor(1);
            }

            List<CommentReplyInfo> commentReplyInfoList = dynamicCommentInfoRedisDao.getCommentReplyInfoByCommentId(id);
            List<CommentReplyDetailInfo> detailInfoList = new ArrayList<>();

            for(CommentReplyInfo obj : commentReplyInfoList){
                CommentReplyDetailInfo detailInfo = new CommentReplyDetailInfo();

                BeanUtils.copyProperties(obj,detailInfo);

                UserCacheVo userCacheVo= userInfoCache.getUserCacheInfo(obj.getReplyFromUserId());


                int year = obj.getReplyTime().getYear();

                String showTime;

                if(nowYear==year){
                    LocalDateTime time = obj.getReplyTime();
                    showTime = time.getMonthValue()+"-"+time.format(DateTimeFormatter.ofPattern("dd HH:mm"));
                }else{
                    showTime = obj.getReplyTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                }
                detailInfo.setReplyFromUserNickName(userCacheVo.getNickName())
                        .setReplyFromUserIcon(userCacheVo.getIcon())
                        .setReplyFromUserAge(userCacheVo.getAge())
                        .setReplyFromUserIsHost(userCacheVo.getIsHost())
                        .setReplyFromUserIsVip(userCacheVo.getIsVip())
                        .setVipLevel(userCacheVo.getVipLevel())
                        .setStar(userCacheVo.getStar())
                        .setReplyFromUserSex(userCacheVo.getSex())
                        .setReplyFromUserMGrade(userCacheVo.getMGrade())
                        .setReplyFromUserVGrade(userCacheVo.getVGrade())
                        .setShowTime(showTime);

                if(detailInfo.getReplyFromUserId().equals(dynamicVo.getUserId())){

                    detailInfo.setIsAuthor(1);
                }
                detailInfoList.add(detailInfo);
            }
            dynamicCommentInfoVo.setReplyInfo(detailInfoList);
            return dynamicCommentInfoVo;
        }else{
            return new HashMap<>(0);
        }

    }

    public Object getDynamicCommentPageByDynamicId(long dynamicId, int page, int pageSize) {
        Map<String,Object> resultMap = new HashMap<>(2);
        int startNum = PageUtil.getOffset(page, pageSize);

        DynamicDetailInfoVo dynamicDetailInfoVo = dynamicInfoRedisDao.getDynamicInfoById(dynamicId);

        if(dynamicDetailInfoVo!=null){
            List<DynamicCommentInfo> dynamicCommentInfoList = dynamicCommentInfoRedisDao
                    .getDynamicCommentPageByDynamicId(dynamicId,startNum,pageSize);

            List<DynamicCommentInfoVo> dynamicCommentInfoVoList = new ArrayList<>();

            if(dynamicCommentInfoList.size()>0){

                for(DynamicCommentInfo obj : dynamicCommentInfoList){

                    DynamicCommentInfoVo dynamicCommentInfoVo = new DynamicCommentInfoVo();

                    setDynamicCommentInfoVo(dynamicCommentInfoVo, obj);

                    if(dynamicDetailInfoVo.getUserId().equals(dynamicCommentInfoVo.getFromUserId())){
                        dynamicCommentInfoVo.setIsAuthor(1);
                    }
                    List<CommentReplyInfo> commentReplyInfoList = dynamicCommentInfoRedisDao
                            .getCommentReplyInfoByCommentId(obj.getId());

                    if (commentReplyInfoList.size() > 0) {

                        Map<String, Object> map = setCommentReplyInfo(commentReplyInfoList.size(), commentReplyInfoList.get(0));

                        dynamicCommentInfoVo.setReplyInfo(map);

                        dynamicCommentInfoVoList.add(dynamicCommentInfoVo);
                    }else{
                        dynamicCommentInfoVoList.add(dynamicCommentInfoVo);
                    }

                }

            }

            int total = dynamicCommentInfoRedisDao.getDynamicCommentPageCountByDynamicId(dynamicId);
            resultMap.put("list",dynamicCommentInfoVoList);
            resultMap.put("total",total);
            return resultMap;
        }else{
            resultMap.put("list",new ArrayList<>());
            resultMap.put("total",0);
            return resultMap;
        }

    }


    /**
     * 设置动态评论基本信息
     * @param dynamicCommentInfoVo
     * @param commentInfo
     */
    public void setDynamicCommentInfoVo(DynamicCommentInfoVo dynamicCommentInfoVo, DynamicCommentInfo commentInfo) {

        int nowYear=LocalDateTime.now().getYear();

        int year = commentInfo.getCommentTime().getYear();

        String showTime;
        if(nowYear==year){
            LocalDateTime time = commentInfo.getCommentTime();
            showTime = time.getMonthValue()+"-"+time.format(DateTimeFormatter.ofPattern("dd HH:mm"));
        }else{
            showTime = commentInfo.getCommentTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        }
        dynamicCommentInfoVo.setCommentId(commentInfo.getId());

        BeanUtils.copyProperties(commentInfo, dynamicCommentInfoVo);

        UserCacheVo commentUserInfo = userInfoCache.getUserCacheInfo(commentInfo.getFromUserId());

        dynamicCommentInfoVo.setFromUserNickName(commentUserInfo.getNickName())
                .setFromUserIcon(commentUserInfo.getIcon())
                .setFromUserAge(commentUserInfo.getAge())
                .setFromUserIsHost(commentUserInfo.getIsHost())
                .setFromUserIsVip(commentUserInfo.getIsVip())
                .setVipLevel(commentUserInfo.getVipLevel())
                .setStar(commentUserInfo.getStar())
                .setFromUserMGrade(commentUserInfo.getMGrade())
                .setFromUserVGrade(commentUserInfo.getVGrade())
                .setFromUserSex(commentUserInfo.getSex())
                .setShowTime(showTime);
    }


    public Map<String, Object> setCommentReplyInfo(int size, CommentReplyInfo commentReplyInfo) {
        UserCacheVo replyFromUserInfo = userInfoCache.getUserCacheInfo(commentReplyInfo.getReplyFromUserId());

        String replyFromUserNickName = replyFromUserInfo.getNickName();

        UserCacheVo replyToUserInfo = userInfoCache.getUserCacheInfo(commentReplyInfo.getReplyToUserId());

        String replyToUserNickName = replyToUserInfo.getNickName();

        Map<String,Object> map = new HashMap<>(2);

        map.put("replyFromUserNickName",replyFromUserNickName);

        map.put("replyToUserNickName",replyToUserNickName);

        map.put("replyContent",commentReplyInfo.getReplyContent());

        map.put("size",size);
        return map;
    }

    /**
     * 检查用户是否可以发送评论
     * @param userId
     * @param number
     */
    public void checkNumber(long userId, int number) {

        UserCacheVo userInfo = userInfoCache.getUserCacheInfo(userId);

        if(userInfo.getIsVip()!=1 &&userInfo.getIsSvip()!=1 && userInfo.getIsPlatinumVip()!=1
                    && userInfo.getIsHost()!=1){
            int sendNumber = dynamicCommentInfoRedisDao.getSendCommentNumber(userId);
            if(sendNumber>=number){
                throw new ConsumeRuntimeException("4111","发送评论超出日限", HttpStatus.OK);
            }
        }
    }

}
